package com.adwin.addcoin.ui.main

import android.content.Intent
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.adwin.addcoin.AddCoinApplication
import com.adwin.addcoin.R
import com.adwin.addcoin.base.BaseFragment
import com.adwin.addcoin.databinding.MainTaskFragmentBinding
import com.adwin.addcoin.repository.bean.CheckInData
import com.adwin.addcoin.repository.bean.HomeTaskBean
import com.adwin.addcoin.ui.adapter.CheckInAdapter
import com.adwin.addcoin.ui.adapter.NewbieMissionAdapter
import com.adwin.addcoin.ui.dialog.CoinsRewardDialog
import com.adwin.addcoin.ui.webview.WebViewActivity
import com.adwin.addcoin.utils.FlowKeyUtils
import com.adwin.addcoin.utils.PersonalMessageUtils
import com.adwin.addcoin.utils.installRepost
import com.adwin.addcoin.utils.log
import com.bumptech.glide.Glide
import com.cashbird.app.infra.utils.FlowBus
import com.google.gson.Gson
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.math.BigDecimal
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger

class TaskFragment : BaseFragment<MainTaskFragmentBinding,TaskFragmentModel> (MainTaskFragmentBinding::inflate,TaskFragmentModel::class.java,false){
    lateinit var binding: MainTaskFragmentBinding
    private var tasks = ArrayList<HomeTaskBean>()
    private val token:String = ""
    private var checkInDay = true
    private var checkList = ArrayList<CheckInData>()
    private var isCheck = AtomicBoolean(false)
    private var check = AtomicInteger(0)
    private var pageNumber = AtomicInteger(1)
    private var images = arrayListOf<String>("https://img2.baidu.com/it/u=1941383634,618713173&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500")
    private var inviteUrl = ""
    private var exchangeUrl = ""
    private var withdrawUrl = ""

    override fun onStart() {
        super.onStart()
        binding.taskBanner.start()

    }

    override fun onStop() {
        super.onStop()
        binding.taskBanner.stop()

    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.taskBanner.destroy()
    }

    override fun initFragment(binding: MainTaskFragmentBinding, savedInstanceState: Bundle?) {
        this.binding = binding
        binding.rvTaskCheckIn.adapter = context?.let { CheckInAdapter(it,checkList) }
        binding.rvTaskCheckIn.addItemDecoration(object : ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                outRect.right = 20
            }
        })
        binding.rvTaskCheckIn.layoutManager =
            LinearLayoutManager(this.context, LinearLayoutManager.HORIZONTAL, false)
        binding.taskBanner.addBannerLifecycleObserver(this)
            .setAdapter(object : BannerImageAdapter<String>(images) {
                override fun onBindView(
                    holder: BannerImageHolder?,
                    data: String?,
                    position: Int,
                    size: Int
                ) {
                    holder?.imageView?.let {
                        Glide.with(it.context).load(R.mipmap.add_coins_banner_icon).into(holder.imageView)
                        holder.imageView.setOnClickListener {
                            startInvite()
                        }
                    }
                }
            })
        binding.rvTaskNewbie.adapter = context?.let {
            NewbieMissionAdapter(tasks, it)
        }
        binding.rvTaskNewbie.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        binding.taskBanner.start()
        myViewModel?.date?.observe(this) {
            lifecycleScope.launch (Dispatchers.IO){
                checkInDay = it.status
                check.set(it.dayNum)
                checkList.clear()
                isCheck.set(it.status)
                var number = 0
                it.rewardDetails?.keys?.iterator()?.forEach { key ->
                    number++
                    val isCheckDe = number <= check.get()
                    val coin = it.rewardDetails?.get(key)?:0
                    val checkData = CheckInData("Day $key",coin,isCheckDe)
                    "isCheckIn ${checkData.isCheckIn}  title:${checkData.dayTitle}".log()
                    checkList.add(checkData)
                }
                "task:${Gson().toJson(checkList)}".log()
                withContext(Dispatchers.Main){
                    myViewModel?.isCheckIn?.value = it.status
                    binding.rvTaskCheckIn.adapter?.notifyDataSetChanged()
                    if (checkInDay){
                        binding.tvCheckInButton.background.setTint(Color.parseColor("#CCCCCC"))
                    }else{
                        binding.tvCheckInButton.background.setTint(Color.parseColor("#F6C139"))
                    }
                }

            }
        }
        PersonalMessageUtils.inviteDetailsBean.observe(this){
            if (it == null) return@observe
            binding.tvNumberInvitees.text = "${it.inviteNum}"
            binding.tvInviteesCoins.text = "${it.inviteCoinNum}"
        }

        myViewModel?.isCheckIn?.observe(this) {isCheckIn ->
            if (isCheckIn){
                try {
                    if (!isCheck.get()){
                        checkList[check.get()].isCheckIn = true
                        binding.rvTaskCheckIn.adapter?.notifyItemChanged(check.get())
                        check.set(check.get()+1)
                        checkInDay = isCheckIn
                        val dayCoins = checkList[check.get()].coins
                        context?.let {
                            CoinsRewardDialog(it,dayCoins).show()
                            FlowBus.with<String>(FlowKeyUtils.CoinsChange).post(lifecycleScope,"")
                        }
                    }
                }catch (e:Exception){

                }
                binding.tvCheckInButton.background.setTint(Color.parseColor("#CCCCCC"))
            }
        }
        binding.includeTopView.tvHomeWithdraw.setOnClickListener {
            startWithdraw()
        }
        binding.viewInviteFriendsBackground.setOnClickListener {
            startInvite()
        }
        if (AddCoinApplication.isCloak){
            binding.includeTopView.tvHomeWithdraw.text = resources.getString(R.string.main_home_exchange_button)
        }else{
            binding.includeTopView.tvHomeWithdraw.text = resources.getString(R.string.main_home_withdraw_button)
        }
        binding.srlTaskRefresh.setRefreshFooter(ClassicsFooter(context))
        binding.srlTaskRefresh.setRefreshHeader(MaterialHeader(context))
        binding.srlTaskRefresh.setOnRefreshLoadMoreListener( object : OnRefreshLoadMoreListener{
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                loading()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                refresh()
            }
        })
        binding.tvCheckInButton.setOnClickListener {
            if (checkInDay) return@setOnClickListener
            myViewModel?.checkIn()
        }
        PersonalMessageUtils.userCoinsBean.observe(this){
            it?.let {
                binding.includeTopView.tvHomeCoin.text = "${BigDecimal(it.coinNum).setScale(0).toString()}"
                binding.includeTopView.tvBonus.text = "= Rp${BigDecimal(it.conversionNum).setScale(2).toString()}"
            }
        }
        myViewModel?.taskLists?.observe(this){
            tasks.clear()
            tasks.addAll(it)
            binding.rvTaskNewbie.adapter?.notifyDataSetChanged()
        }
        myViewModel?.isLoad?.observe(this){
            binding.srlTaskRefresh.setEnableLoadMore(it)
        }
        myViewModel?.isRefresh?.observe(this){
            if (!it){
                binding.srlTaskRefresh.finishRefresh()
                binding.srlTaskRefresh.finishLoadMore()
            }
        }
        if (AddCoinApplication.isCloak){
            binding.includeTopView.tvBonus.visibility = View.GONE
        }else{
            binding.includeTopView.tvBonus.visibility = View.VISIBLE
        }
        PersonalMessageUtils.appDispositionBean.observe(this){appDisposition ->
            if (appDisposition != null){
                inviteUrl = appDisposition.INVITE
                exchangeUrl = appDisposition.EXCHANGE
                withdrawUrl = appDisposition.WITHDRAW
            }
        }
        FlowBus.with<String>(FlowKeyUtils.taskChange).register(lifecycle){
            refresh()
        }
        refresh()
    }

    private fun startInvite(){
        if (TextUtils.isEmpty(inviteUrl)) return
        MainScope().launch (Dispatchers.IO){
            val obj = JSONObject()
            obj.put("addCoinUrl",inviteUrl)
            context?.installRepost("taskInviteClick",obj)
        }
        val intent = Intent(context,WebViewActivity::class.java)
        intent.putExtra("url",inviteUrl)
        startActivity(intent)
    }
    private fun startWithdraw(){
        val intent = Intent(context, WebViewActivity::class.java)
        if (AddCoinApplication.isCloak){
            if (TextUtils.isEmpty(exchangeUrl)) return
            MainScope().launch (Dispatchers.IO){
                val obj = JSONObject()
                obj.put("addCoinUrl",exchangeUrl)
                context?.installRepost("taskExchangeClick",obj)
            }
            intent.putExtra("url",exchangeUrl)
        }else{
            if (TextUtils.isEmpty(withdrawUrl)) return
            MainScope().launch (Dispatchers.IO){
                val obj = JSONObject()
                obj.put("addCoinUrl",withdrawUrl)
                context?.installRepost("taskWithdrawUrlClick",obj)
            }
            intent.putExtra("url",withdrawUrl)
        }
        startActivity(intent)
    }

    /**
     * 刷新数据
     */
    private fun refresh(){
        myViewModel?.getCheckMessage()
        myViewModel?.getInviteRewards()
        myViewModel?.getCoinActivityList(pageNumber.get())
    }

    /**
     * 加载更多
     */
    private fun loading(){
        pageNumber.set(pageNumber.get()+1)
        myViewModel?.getCoinActivityList(pageNumber.get())
    }

    override fun onBackPressed(): Boolean = true
}